﻿using Futajma.MigrationStudio.GenericPersistance;
using Futajma.MigrationStudio.GenericPersistance.Data;
using Microsoft.SharePoint.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace Futajma.MigrationStudio.SharePointPersistance
{
    public class SharePoint2010TemplateStructureLoader : GenericTemplateStructureLoader
    {
        public override void SaveDefinition(object target)
        {
            var filename = target as string;

            if (!string.IsNullOrEmpty(filename))
            {

                XmlWriterSettings settings = new XmlWriterSettings();
                settings.Encoding = new UnicodeEncoding(false, false); // no BOM in a .NET string
                settings.Indent = true;
                //settings.OmitXmlDeclaration = true;

                XmlSerializer serializer = new XmlSerializer(typeof(List<SiteCollectionTemplate>));

                using (XmlWriter writer = XmlWriter.Create(filename, settings))
                {
                    serializer.Serialize(writer, TemplateDefinition.Instance.SiteCollectionDefinitions);
                }
            }
        }

        //public bool LoadDefinition(object source)
        //{
        //    //GenericPersistance.Data.TemplateDefinition ret = new GenericPersistance.Data.TemplateDefinition();
            
        //    if (!LoadTemplateDefinition())
        //    {
        //        BuildDefaultDefinition();
        //    }
        //}

        //public void BuildDefaultDefinition()
        //{
        //    GenericPersistence.Data.TemplateDefinition.Instance.Clear();

        //    var scDef = new SiteCollectionTemplate();
        //    scDef.ID = new Guid("{962FC9F6-8164-46BE-BBD2-1F9BDE43932D}");
        //    scDef.Name = "John Deere Template";
        //    scDef.RootSiteTemplate = new SiteTemplate() { Name = "Root Site Definition", ID = new Guid("{1CD9DAC6-4E8D-47F6-86A1-339E7E1D7A2D}"), CreateAsDefault = false };

        //    scDef.RootSiteTemplate.LibraryTemplates.Add(new LibraryTemplate() { Name = "Shared Documents", ID = new Guid("{F5FCBBC3-FAB9-40BE-A5CC-0BAAAF6FFBDB}"), CreateAsDefault = false });
        //    scDef.RootSiteTemplate.LibraryTemplates.Add(new LibraryTemplate() { Name = "Authorization Documents", ID = new Guid("{9EF9E2D9-A188-4810-9213-DBAC9B7B7649}"), CreateAsDefault = true, CreateFolderAllowed = true });

        //    //scDef.Groups.Add(new Group() { Name = "Site Owners", ID = new Guid("{3F3FE50C-0CFB-405F-873C-7E42CA5996B5}") });
        //    //scDef.Groups.Add(new Group() { Name = "Site Members", ID = new Guid("{472283F3-C457-4BF1-B934-D9D10C3D32BE}") });
        //    //scDef.Groups.Add(new Group() { Name = "Site Visitors", ID = new Guid("{20DFBD06-4D19-432F-A106-463378F1CEB3}") });

        //    var sDef = new SiteTemplate() { Name = "Site Definition 1", ID = new Guid("{F898F63C-88E2-4DDD-A50E-540870C34EB5}"), CreateAsDefault = true };
        //    scDef.SiteTemplates.Add(sDef);
        //    sDef.LibraryTemplates.Add(new LibraryTemplate() { Name = "Shared Documents", ID = new Guid("{A5BB01AF-5AFC-4A21-AEE0-2D3702180E67}"), CreateAsDefault = true });
        //    sDef.LibraryTemplates.Add(new LibraryTemplate() { Name = "authorization Documents", ID = new Guid("{2B095FF7-3005-49D2-A0A0-CC9167FC8339}"), CreateAsDefault = false });
        //    sDef.SiteTemplates.Add(new SiteTemplate() { Name = "John Deere 9630 Sub Site", ID = new Guid("{CA5B2854-CC98-42CB-B36F-D9F5D6DD83A2}"), CreateAsDefault = true });
        //    sDef = new SiteTemplate() { Name = "Site Definition 2", ID = new Guid("{E7188CB4-0AF4-46F7-BCE8-9A20C792C218}"), CreateAsDefault = false };
        //    scDef.SiteTemplates.Add(sDef);
        //    sDef.LibraryTemplates.Add(new LibraryTemplate() { Name = "Shared Documents internal", ID = new Guid("{5DEC43E5-41D8-46C2-8780-074020332018}"), CreateAsDefault = true });
        //    sDef.LibraryTemplates.Add(new LibraryTemplate() { Name = "Study Documents internal", ID = new Guid("{08101197-5168-42D8-89CE-457A074C36E6}"), CreateAsDefault = false });

        //    //scDef.ListTemplates.Add(new SubTemplate() { Name = "Shared Documents", ID = "1", CreateAsDefault = true });
        //    //scDef.ListTemplates.Add(new SubTemplate() { Name = "Study Documents", ID = "2", CreateAsDefault = true });

        //    GenericPersistence.Data.TemplateDefinition.Instance.SiteCollectionDefinitions.Add(scDef);

        //    scDef = new SiteCollectionTemplate();
        //    scDef.Name = "Project Template";
        //    scDef.ID = new Guid("{87988C2B-AF08-4791-AF43-CA3E21741B33}");
        //    scDef.RootSiteTemplate = new SiteTemplate() { Name = "Root Site Definition", ID = new Guid("{C018D0BE-0F37-411A-B5E3-BBD821EF549E}"), CreateAsDefault = false };
        //    scDef.RootSiteTemplate.LibraryTemplates.Add(new LibraryTemplate() { Name = "Default Document Library", ID = new Guid("{D94E501B-6DB4-42D5-A952-B162AC130DF6}"), CreateAsDefault = false });
        //    scDef.RootSiteTemplate.LibraryTemplates.Add(new LibraryTemplate() { Name = "Documents", ID = new Guid("{19749A41-9D11-4DCE-9C0E-CB63A0BAD642}"), CreateAsDefault = true, NotShownAsCreateNewLibrary = true });
        //    scDef.RootSiteTemplate.LibraryTemplates.Add(new LibraryTemplate() { Name = "Meetings", ID = new Guid("{A0F63B19-719A-46FE-A5B0-A4FE1E9144DD}"), CreateAsDefault = true, CreateFolderAllowed = true, NotShownAsCreateNewLibrary = true });

        //    GenericPersistence.Data.TemplateDefinition.Instance.SiteCollectionDefinitions.Add(scDef);

        //    scDef = new SiteCollectionTemplate();
        //    scDef.Name = "Massey Ferguson Template";
        //    scDef.ID = new Guid("{65A658ED-2B54-41B6-9E1B-FF992F76619D}");
        //    scDef.RootSiteTemplate = new SiteTemplate() { Name = "Root Site Definition", ID = new Guid("{3D8D32C1-FD36-4941-A820-8152151190A8}"), CreateAsDefault = false };
        //    scDef.RootSiteTemplate.LibraryTemplates.Add(new LibraryTemplate() { Name = "Default Document Library", ID = new Guid("{C90CD402-9903-4860-BEDC-1026B9082083}"), CreateAsDefault = false });
        //    scDef.RootSiteTemplate.LibraryTemplates.Add(new LibraryTemplate() { Name = "Documents", ID = new Guid("{53F52747-DE3C-4DB8-ABA8-1FE503625398}"), CreateAsDefault = true, NotShownAsCreateNewLibrary = true });

        //    GenericPersistence.Data.TemplateDefinition.Instance.SiteCollectionDefinitions.Add(scDef);

        //    scDef = new SiteCollectionTemplate();
        //    scDef.Name = "Meili Template";
        //    scDef.ID = new Guid("{D4292B3B-6F88-4DF2-8371-ACFEB1E97743}");
        //    scDef.RootSiteTemplate = new SiteTemplate() { Name = "Root Site Definition", ID = new Guid("{F42F5BC4-D3A5-445B-8A9D-10D9D8AFFB9D}"), CreateAsDefault = false };
        //    scDef.RootSiteTemplate.LibraryTemplates.Add(new LibraryTemplate() { Name = "Meili VBM 22 Document Library", ID = new Guid("{779F40A5-D763-4954-9583-D23233BEBA95}"), CreateAsDefault = false });
        //    scDef.RootSiteTemplate.LibraryTemplates.Add(new LibraryTemplate() { Name = "Documents", ID = new Guid("{DB71709C-EC95-483B-8022-6BC1E18399AC}"), CreateAsDefault = true, NotShownAsCreateNewLibrary = true });
        //    scDef.RootSiteTemplate.LibraryTemplates.Add(new LibraryTemplate() { Name = "Meetings", ID = new Guid("{5205FFE6-AEBF-4303-9EDC-98CB1C9837A7}"), CreateAsDefault = true, CreateFolderAllowed = true, NotShownAsCreateNewLibrary = true });

        //    GenericPersistence.Data.TemplateDefinition.Instance.SiteCollectionDefinitions.Add(scDef);
        //}

        public override bool LoadDefinition(object source)
        {
            ExtendedClientContext clientContext = new ExtendedClientContext(Settings.MigrationPortalUrl);

            Web oWebsite = clientContext.Web;
            ListCollection collList = oWebsite.Lists;

            List oList = collList.GetByTitle(Settings.ConfigurationListTitle);

            CamlQuery camlQuery = new CamlQuery();
            camlQuery.ViewXml = string.Format("<View><Query><Where><Eq>" +
                "<FieldRef Name='Title'/><Value Type='Text'>{0}</Value>" +
                "</Eq></Where></Query></View>", Settings.TemplateDefinitionDataItemTitle);

            ListItemCollection collListItem = oList.GetItems(camlQuery);
            clientContext.Load(oList);
            clientContext.Load(collListItem,
                items => items.IncludeWithDefaultProperties(
                item => item.DisplayName));

            clientContext.ExecuteQuery();

            if (collListItem.Count > 0)
            {
                var fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, (string)collListItem[0]["FileRef"]);

                XmlSerializer serializer = new XmlSerializer(typeof(List<SiteCollectionTemplate>));

                using (XmlReader reader = XmlReader.Create(fileInfo.Stream))
                {
                    TemplateDefinition.Instance.SiteCollectionDefinitions = (List<SiteCollectionTemplate>)serializer.Deserialize(reader);
                    //var governanceData = (GovernanceData)serializer.Deserialize(reader);
                    //return governanceData;
                    return true;
                }

            }
            return false;
        }

    }
}
